package src.Client;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Random;

import src.Client.YYChatClientConnection;
import src.User.User;
import src.User.UserType;
import src.common.DBUtil;
import src.common.MessageType;
import src.common.Regex;
import src.common.impl.Message;

public class ClientLogin extends JFrame implements ActionListener {

    public static HashMap<String, FriendList> hmFriendList = new HashMap();
    JLabel jl;
    JButton jbl,jb2,jb3,jb_phone;
    JPanel jp;
    JLabel j11,j12,j13,j14;
    JLabel j11_phone,j12_phone,j13_phone,j14_phone;
    JLabel JPhone,jph12,jph13,jph14;
    JTextField jtf,jtf_phone;
    JPasswordField jpf,jpf_phone;
    JButton jb4,jb4_phone;
    JCheckBox jcl,jc2;
    JPanel jp1, jp2,jp3,jp_phone;
    JTabbedPane jtp;
    public ClientLogin(){

        jl=new JLabel (new ImageIcon ("src/images/head.gif") ) ;
        this.add(jl, "North");

        j11=new JLabel ("YY 号码：",JLabel. CENTER);
        j12=new JLabel ("YY 密码：",JLabel. CENTER);
        j13=new JLabel ("忘记密码",JLabel.CENTER);
        j13.setForeground (Color .blue) ; //设置字体蓝色
        j14=new JLabel ("申请密码俣护",JLabel. CENTER);
        jb4=new JButton(new ImageIcon("src/images/clear.gif"));
        jtf=new JTextField();
        jpf=new JPasswordField();
        jcl=new JCheckBox ("隐身登陆");
        jc2=new JCheckBox ("记住密码");
        jp1=new JPanel (new GridLayout (3, 3) ) ;//设置网格布局模式
        jp1.add(j11) ; jp1.add(jtf) ; jp1. add (jb4) ; jp1.add(j12);
        jp1.add(jpf);
        jp1.add(j13);
        jp1.add(jcl);
        jp1.add(jc2);
        jp1.add(j14);

        JPhone=new JLabel ("手机号码：",JLabel. CENTER);
        j12_phone=new JLabel ("YY 密码：",JLabel. CENTER);
        j13_phone=new JLabel ("忘记密码",JLabel.CENTER);
        j13_phone.setForeground (Color .blue) ; //设置字体蓝色
        j14_phone=new JLabel ("申请密码俣护",JLabel. CENTER);
        jb4_phone=new JButton(new ImageIcon("src/images/clear.gif"));
        jtf_phone=new JTextField();
        jpf_phone=new JPasswordField();
        jp_phone=new JPanel (new GridLayout (3, 3) ) ;//设置网格布局模式
        jp_phone.add(JPhone) ;
        jp_phone.add(jtf_phone) ;
        jp_phone. add (jb4_phone) ;
        jp_phone.add(j12_phone);
        jp_phone.add(jpf_phone);
        jp_phone.add(j13_phone);
        jp_phone.add(j14_phone);


        jtp=new JTabbedPane () ; //创建选项卡面板
        jtp.add("YY号码",jp1);
        jtp.add ("手机号码",jp_phone);
        jtp.add ("电子邮箱",jp3);
        this.add(jtp,"Center");



        jbl=new JButton (new ImageIcon ("src/images/login.gif") ) ;
        jbl.addActionListener(this);

        jb2=new JButton(new ImageIcon("src/images/register.gif"));
        jb2.addActionListener(this);

        jb3=new JButton(new ImageIcon("src/images/cancel.jpg"));
        jp=new JPanel ();//创建面板对象

        jb_phone=new JButton(new ImageIcon("src/images/login.gif"));
        jb_phone.addActionListener(this);


        jp.add(jb_phone);
        jp.add (jb2);
        jp.add(jb3);
        this.add (jp, "South") ;//JPanel 组件添力口至！J窗体南部
        Image im=new ImageIcon("src/images/duck2.gif").getImage();

        this. setIconImage(im) ; //设置窗体左上角图标
        //this. setBounds (800 , 600, 350, 250) ;
        this. setLocationRelativeTo (null) ;//设置相对位置为 null
        this.setSize (350,250);
        this. setDefaultCloseOperation (EXIT_ON_CLOSE) ;//点击窗体的关闭按 钮，退出程序	一 一
        this. setTitle ("YY聊天");//设置窗体标题
        this. setVisible (true) ;//窗体可视 )
    }

    public static void main(String[] args) {
        new ClientLogin () ;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String name = jtf.getText();
        String password = new String(jpf.getPassword());
        User user = new User();
        user.setUsername(name);
        user.setPassword(password);
        String phone = jtf_phone.getText();
        user.setPhone(phone);


        if (e.getSource() == jb_phone){
            // 以下是添加窗口抖动效果的代码开始
            Point originalLocation = this.getLocation(); // 获取窗口原始位置
            Random random = new Random();
            int shakeCount = 10; // 定义抖动次数
            int shakeRange = 5; // 定义抖动范围（像素）
            for (int i = 0; i < shakeCount; i++) {
                int offsetX = random.nextInt(shakeRange * 2) - shakeRange; // 随机生成水平方向偏移量
                int offsetY = random.nextInt(shakeRange * 2) - shakeRange; // 随机生成垂直方向偏移量
                this.setLocation(originalLocation.x + offsetX, originalLocation.y + offsetY);
                try {
                    Thread.sleep(20); // 短暂停顿，控制抖动速度
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
            this.setLocation(originalLocation); // 恢复到原始位置

            if (!Regex.checkPhone(phone)){
                JOptionPane.showMessageDialog(this, "手机号号码格式错误！");
                return;
            }

            password = new String(jpf_phone.getPassword());
            user.setPassword(password);
            user.setUserType(UserType.USER_LOGIN_BY_PHONE);
            DBUtil.getUserNameByPhone(user.getPhone(),password,user);
            Message message = new YYChatClientConnection().loginByPhone(user);
            if (message.getMessageType().equals(MessageType.LOGIN_SUCCESS)){
                String allFriends = message.getContent();
                FriendList friendList = new FriendList(name, allFriends);
                hmFriendList.put(name, friendList);
                this.dispose();

            }else {
                JOptionPane.showMessageDialog(this, "用户名或密码错误！");
            }

        }


        if (e.getSource() == jbl){
            // 以下是添加窗口抖动效果的代码开始
            Point originalLocation = this.getLocation(); // 获取窗口原始位置
            Random random = new Random();
            int shakeCount = 10; // 定义抖动次数
            int shakeRange = 5; // 定义抖动范围（像素）
            for (int i = 0; i < shakeCount; i++) {
                int offsetX = random.nextInt(shakeRange * 2) - shakeRange; // 随机生成水平方向偏移量
                int offsetY = random.nextInt(shakeRange * 2) - shakeRange; // 随机生成垂直方向偏移量
                this.setLocation(originalLocation.x + offsetX, originalLocation.y + offsetY);
                try {
                    Thread.sleep(20); // 短暂停顿，控制抖动速度
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
            this.setLocation(originalLocation); // 恢复到原始位置
            user.setUserType(UserType.USER_LOGIN_VALIDATE);
            Message message = new YYChatClientConnection().loginValidate(user);
            if (message.getMessageType().equals(MessageType.LOGIN_SUCCESS)){
                String allFriends = message.getContent();
                FriendList friendList = new FriendList(name, allFriends);
                hmFriendList.put(name, friendList);
                this.dispose();

            }else {
                JOptionPane.showMessageDialog(this, "用户名或密码错误！");
            }

        }
        if (e.getSource() == jb2){
            user.setUserType(UserType.USER_REGISTER);
            if (new YYChatClientConnection().registerUser(user)){
                JOptionPane.showInternalMessageDialog(this,name+"用户注册成功!!!");
            }else {
                JOptionPane.showInternalMessageDialog(this,name+"用户名重复,注册失败!!!");
            }
        }
    }

    public void sendMessage(Socket s,Message message){
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(s.getOutputStream());
            oos.writeObject(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
